<template>
  <div class="body-speech">
    <el-button type="success" @click="eanble()">开启录音</el-button>
  </div>
  <div style="display: flex;justify-content: center;align-items: center;">
    <div style="border: 1px solid black;width: 1200px;height: 350px;">
      {{speechArr.join(" ")}}
    </div>
  </div>
</template>

<script setup>


import {enableJs} from "../api/speech/speech.js";
import {ElMessage} from "element-plus";
import {onBeforeUnmount, onMounted, ref} from "vue";

// 开启语音录制
function eanble() {
  enableJs().then(res => {
    if (res.data.code == 200) {
      ElMessage.success("开启成功")
    }
  })
}
// 定义数组
// WebSocket 实例
const socket = ref(null);
// 存储 WebSocket 消息
const messages = ref([]);
// 这是将要存储在数据库中的数据
var speechArr = ref([])

// 创建 WebSocket 连接
const connectWebSocket = () => {
  socket.value = new WebSocket('ws://localhost:8081/websocket');

  // WebSocket 打开连接时
  socket.value.onopen = () => {
    console.log('WebSocket 连接已打开');
  };

  // WebSocket 接收到消息时
  socket.value.onmessage = (event) => {
    console.log('收到消息:', event.data);
    messages.value.push(event.data);
    speechArr.value.push(event.data)
  };

  // WebSocket 错误时
  socket.value.onerror = (error) => {
    console.error('WebSocket 错误:', error);
  };

  // WebSocket 连接关闭时
  socket.value.onclose = () => {
    console.log('WebSocket 连接已关闭');
  };
};

// 发送消息到 WebSocket
/*const sendMessage = () => {
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    socket.value.send('启动互联通知');
  } else {
    console.error('WebSocket 未连接');
  }
};*/

// 组件挂载时建立 WebSocket 连接
onMounted(() => {
  connectWebSocket();
});

// 组件卸载时关闭 WebSocket 连接
onBeforeUnmount(() => {
  if (socket.value) {
    socket.value.close();
  }
});


</script>

